<script setup>
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer,
  LegendComponent,
  LineChart,
  DataZoomComponent
])
import { onBeforeUnmount, onMounted, reactive, watch } from 'vue'
let chartInstance = null
const props = defineProps(['data', 'eid'])
const option = reactive({
  grid: {
    top: '15%',
    bottom: '20',
    containLabel: true
  },
  tooltip: {
    backgroundColor: 'rgba(0, 0, 0, 0.6)', // 半透明黑色背景
    textStyle: {
      color: '#fff' // 白色字体
    },
    trigger: 'axis',
    triggerOn: 'click',
    className:'',
    formatter: function (params) {
      let template = ``
      params.map((item) => {
        template += `<div>${item.axisValue}<br/> ${item.value} 件</div>`
      })
      return template
    }
  },
  color: ['#36B374', '#FF8C19'],
  legend: {
    y: 'bottom',
    x: 'center',
    itemHeight: 7
  },
  xAxis: {
    axisTick: {
      show: false // 不显示坐标轴刻度
    },
    axisLine: {
      lineStyle: {
        type: 'dashed',
        color: '#E0E0E0'
      }
    },
    axisLabel: {
      fontSize: 12,
      color: '#71747A'
    },
    type: 'category',
    boundaryGap: false,
    // 一个月的数据
    data: []
  },
  yAxis: {
    type: 'value',
    name: '单位（件）',
    margin: 8,
    nameGap: 20,
    nameTextStyle: {
      fontSize: 14, // 设置名称的字体大小
      color: '#9DA0A4' // 设置名称的颜色
    },
    axisLabel: {
      fontSize: 14,
      color: '#9DA0A4'
    },
    axisLine: {
      show: false
    },
    axisTick: {
      show: false // 不显示坐标轴刻度
    }
  },
  series: [
    {
      name: '2024',
      type: 'line',
      // 30个数据
      data: [],
      markPoint: {
        data: [
          { type: 'max', name: 'Max' },
          { type: 'min', name: 'Min' }
        ]
      }, // 转折点标记
      markLine: {
        data: [{ type: 'average', name: 'Avg' }] // 平均线
      }
    }
  ],
  dataZoom: [
    {
      type: 'inside', // slider表示有滑动块的，inside表示内置的
      show: true,
      xAxisIndex: [0],
      start: 0,
      end: 50,
      backgroundColor: 'rgba(0,0,0,0.5)', // 滑块背景颜色
      fillerColor: 'rgba(255,255,0,0.5)', // 填充颜色
      showDetail: false // 拖拽时，是否显示详细信息
    }
  ]
})

onMounted(() => {
  option.series[0].data = props.data.seriesData
  option.xAxis.data = props.data.xData
  chartInstance = echarts.init(document.getElementById(props.eid))
  updateChart()
  window.addEventListener('resize', canalDebounce)
})

watch(
  () => props,
  (newVal) => {
    if (newVal.data.seriesData.length === 0) {
      option.title = {
        text: '暂无数据',
        x: 'center',
        y: 'center',
        textStyle: {
          fontSize: 20,
          fontWeight: 'normal',
          color: 'white'
        }
      }
    } else {
      option.title = {}
    }
    option.series[0].data = newVal.data.seriesData
    option.xAxis.data = newVal.data.xData
    updateChart()
  },
  { deep: true }
)

//页面销毁前，销毁事件和实例
onBeforeUnmount(() => {
  window.removeEventListener('resize', canalDebounce)
  // chartInstance.dispose()
})

const updateChart = () => {
  if (chartInstance) {
    chartInstance.setOption(option)
  }
}
const resizeHandler = () => {
  chartInstance.resize()
}
//设置防抖，保证无论拖动窗口大小，只执行一次获取浏览器宽高的方法
const debounce = (fun, delay) => {
  let timer
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fun()
    }, delay)
  }
}
const canalDebounce = debounce(resizeHandler, 500)
</script>

<template>
  <section class="bar-chart-box relative p-0 m-0">
    <div
      class="absolute top-0px right-20px text-12px font-400 leading-12px text-#9DA0A4"
    >
      向右拖动可查看全部
    </div>
    <div :id="props.eid" style="width: 95%; height: 60vw; z-index: 90" />
  </section>
</template>

<style scoped>
.bar-chart-box {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  margin-bottom: 20px;
  width: 100%;
  padding: 0;
}
</style>
